#!/usr/bin/env python
# coding: utf-8

# æ”¯çº¿ä»»åŠ¡ä½†æ˜¯ç´§æ€¥
# - task1:
#     é…ç½®seleniumï¼ˆä»Šå¤©ï¼‰
# - task2ï¼š
#     è·‘é€šPinterestï¼Œè‡ªåŠ¨æ³¨å†Œè´¦å·ä»¥åŠåˆ‡æ¢IPçš„æµç¨‹ï¼ˆçœ‹æ‡‚ï¼Œä»Šå¤©è·‘é€šï¼‰
# - task3:
#     åˆ©ç”¨selenium+ [beautiful soup](https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/) æŠ“å–[amz123å…³é”®è¯](https://www.amz123.com/usatopkeywords)ï¼ˆæ˜Žå¤©ï¼‰
#
# ä¸»çº¿ä»»åŠ¡ä½†æ˜¯ç¼“å’Œ
# - task4ï¼ˆä¼˜å…ˆçº§ä½Žï¼‰:
#     åˆ©ç”¨selenium+scrapy,è·‘é€šmover&shaker.py, å½“å‰çš„æ•°æ®å­˜å‚¨åœ¨æœ¬åœ°ï¼Œç›®çš„ï¼šæŠ“å–æ•°æ®åŽç›´æŽ¥å­˜å‚¨åˆ°å¯¹åº”çš„æ•°æ®åº“
#
# - task5 (ä¼˜å…ˆçº§ä½Žï¼‰:
#     ä¸Šå‡æ¦œæ•°æ®æ•´åˆ

# In[20]:


# email.txt to redis


# In[45]:


import json
import time
from time import sleep
from loguru import logger
from redis_queue import RedisQueue
from ast import literal_eval
from pprint import pprint as print
from random import randint

from scrapy.selector import Selector
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import Select

from aws_ip_shifter import ElasticIPController, get_instance_id

chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox')

logger.add("signup.log")


class Config(object):
    redis_conf = {
        "host": "r-bp1e8lecdfhttng2pbpd.redis.rds.aliyuncs.com",
        "port": 6999,
        "db": 6,
        "password": "redis123@"
    }


redis_conf = Config.redis_conf
instance_id = get_instance_id()
ip_controller = ElasticIPController(instance_id)


# In[22]:


# parse email
def parser(email_file):
    with open(email_file, 'r', encoding='utf-8') as f:
        data = f.readlines()
    data = [tuple(i.strip().split('----')) for i in data]
    return data


# In[23]:


# input func
def push_to_queue(data, queue_name='rq'):
    '''
        data: List[tuple]
    '''
    q = RedisQueue(queue_name, redis_conf)  # æ–°å»ºé˜Ÿåˆ—åä¸ºrq
    for i, info in enumerate(data):
        q.put(info)
        logger.info(f"push {i}th info to {queue_name} queue")
    return


# In[24]:


# output func
def pop_from_queue(queue_name='rq'):
    q = RedisQueue(queue_name, redis_conf)
    while 1:
        result = literal_eval(q.get_nowait())
        if not result:
            break
        logger.info(f"Current deal with email: {result[0]} - password: {result[1]}")
        yield result


# In[31]:


class SignupRobot:
    def __init__(self, email, password, code, age, instanceip):
        self.email = email
        self.password = password
        self.code = code
        self.age = age
        self.ip = instanceip
        self.driver = webdriver.Chrome(options=chrome_options)
        # self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(10)

    def basic_info_signup(self):
        driver = self.driver
        # open pinterest
        register_url = "https://www.pinterest.com/"
        driver.get(register_url)

        # click signup button
        driver.find_element_by_xpath(
            "//div[@id='__PWS_ROOT__']/div/div/div/div/div[3]/div/div/div[2]/div[2]/button/div").click()
        # input email
        driver.find_element_by_id("email").clear()
        driver.find_element_by_id("email").send_keys(self.email)

        # input password
        driver.find_element_by_id("password").clear()
        driver.find_element_by_id("password").send_keys(self.password)

        # input age
        driver.find_element_by_id("age").clear()
        driver.find_element_by_id("age").send_keys(self.age)

        # click continue button
        driver.find_element_by_xpath(
            "//div[@id='__PWS_ROOT__']/div/div/div/div/div[3]/div/div/div/div/div/div/div/div[4]/div/div/form/div[4]/button/div").click()

    def choose_lang_region(self):
        driver = self.driver
        driver.find_element_by_xpath("//div[2]/button/div").click()

        driver.find_element_by_xpath("//h3").click()

        driver.find_element_by_id("newUserLanguage").click()
        Select(driver.find_element_by_id("newUserLanguage")).select_by_visible_text("English (US)")
        driver.find_element_by_id("newUserCountry").click()
        Select(driver.find_element_by_id("newUserCountry")).select_by_visible_text("United States")

        driver.find_element_by_xpath("//div[2]/button/div").click()

    def choose_tag(self):
        driver = self.driver
        driver.find_element_by_xpath("//div[5]/div/div/div/div/div/div/div/div/div/div/button/div").click()
        driver.find_element_by_xpath("//div/div[2]/div/div/div/div/div/div/button/div").click()
        driver.find_element_by_xpath("//div[6]/div/div/div/div/div/div/button/div").click()
        driver.find_element_by_xpath("//div[7]/div/div/div/div/div/div/button/div").click()
        driver.find_element_by_xpath("//div[9]/div/div/div/div/div/div/button/div").click()
        driver.find_element_by_xpath("//div[2]/button/div").click()
        driver.quit()

    def signup(self):
        try:
            driver = self.basic_info_signup()
        except Exception as e:
            logger.debug(f"basic signup func error: {e}")
            push_to_queue([(self.email, self.password, self.code)], queue_name='rq')
        else:
            sleep(5)
            try:
                driver = self.choose_lang_region()
                self.choose_tag()
            except Exception as e:
                logger.debug(f"choose func error: {e}")
                push_to_queue([(self.email, self.password, self.code, self.ip)], queue_name='halfcomplete')

            else:
                sleep(5)
                try:
                    username = check_login(self.email, self.password)
                    push_to_queue([(self.email, self.password, self.code, self.ip)], queue_name='complete')
                    return username, self.email, self.password
                except Exception as e:
                    logger.debug(f"login check func error: {e}")


# In[32]:


def check_login(email, password):
    driver = webdriver.Chrome()
    driver.implicitly_wait(30)
    driver.get("https://www.pinterest.com/")
    driver.find_element_by_xpath(
        "//div[@id='__PWS_ROOT__']/div/div/div/div/div[3]/div/div/div[2]/div/button/div").click()

    driver.find_element_by_id("email").clear()
    driver.find_element_by_id("email").send_keys(email)

    driver.find_element_by_id("password").clear()
    driver.find_element_by_id("password").send_keys(password)
    driver.find_element_by_xpath("//button[@type='submit']").click()
    sleep(10)
    response = Selector(text=driver.page_source)
    username = response.css('.GestaltTouchableFocus::attr(href)').extract()
    driver.quit()
    return username


# In[33]:


def check_status(status, email):
    if status:
        user_info = status[-1]
        if user_info.strip('/') in email:
            return 'success'
        else:
            return 'fail'


# In[41]:


def autosignup(instanceip):
    email, password, code = next(pop_from_queue())
    age = randint(18, 35)

    signrobot = SignupRobot(email, password, code, age, instanceip)
    res = signrobot.signup()
    if res:
        res, email, password = res
        status = check_status(res, email)
        logger.info(f"signup accout: {email} - password: {password} - ip: {instanceip} - status: {status}")


# In[43]:


autosignup(ip_controller.instanceip)

ip1 = ip_controller.change_address()

autosignup(ip_controller.instanceip)

ip2 = ip_controller.rollback()

autosignup(ip_controller.instanceip)

# In[ ]:




